﻿using System;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace TK.Common.Json
{
    /// <summary>
    /// TimeSpan
    /// </summary>
    public class TimeSpanConverter : JsonConverter<TimeSpan>
    {
        /// <summary>
        /// 反序列化
        /// </summary>
        public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            if (reader.TokenType == JsonTokenType.String && typeToConvert == typeof(TimeSpan))
            {
                return TimeSpan.Parse(reader.GetString());
            }

            throw new NotSupportedException();
        }

        /// <summary>
        /// 序列化
        /// </summary>
        public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString(@"hh\:mm"));
        }
    }
}
